package service

import (
	"context"
	"shop-demo/app/product/service/internal/biz"

	pb "shop-demo/api/product/v1"
)

type ProductService struct {
	uc *biz.ProductUseCase
	pb.UnimplementedProductServer
}

func NewProductService(uc *biz.ProductUseCase) *ProductService {
	return &ProductService{
		uc: uc,
	}
}

func (s *ProductService) CreateProduct(ctx context.Context, req *pb.CreateProductReq) (*pb.CreateProductReply, error) {
	product, err := s.uc.CreateProduct(ctx, &biz.Product{
		Name: req.Name,
		Num:  req.Num,
	})
	if err != nil {
		return nil, err
	}
	return &pb.CreateProductReply{
		Id: product.Id,
	}, nil
}

func (s *ProductService) UpdateProduct(ctx context.Context, req *pb.UpdateProductReq) (*pb.UpdateProductReply, error) {
	product, err := s.uc.UpdateProduct(ctx, &biz.Product{
		Id:  req.Id,
		Num: req.Num,
	})
	if err != nil {
		return nil, err
	}
	return &pb.UpdateProductReply{
		Id:  product.Id,
		Num: product.Num,
	}, nil
}

func (s *ProductService) DeleteProduct(ctx context.Context, req *pb.DeleteProductReq) (*pb.DeleteProductReply, error) {
	err := s.uc.DeleteProduct(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	return &pb.DeleteProductReply{}, nil
}

func (s *ProductService) GetProduct(ctx context.Context, req *pb.GetProductReq) (*pb.GetProductReply, error) {
	product, err := s.uc.GetProduct(ctx, req.Id)
	if err != nil {
		return nil, err
	}
	return &pb.GetProductReply{
		Id:   product.Id,
		Num:  product.Num,
		Name: product.Name,
	}, nil
}

func (s *ProductService) ListProduct(ctx context.Context, req *pb.ListProductReq) (*pb.ListProductReply, error) {
	products, err := s.uc.ListProduct(ctx, req.PageNum, req.PageSize)
	if err != nil {
		return nil, err
	}
	var replyProducts = make([]*pb.ListProductReply_Product, 0, len(products))
	for _, product := range products {
		replyProducts = append(replyProducts, &pb.ListProductReply_Product{
			Id:   product.Id,
			Num:  product.Num,
			Name: product.Name,
		})
	}
	return &pb.ListProductReply{Products: replyProducts}, nil
}
